<?php

namespace common\behavior\CommonMessagePushing;


use common\model\EntityModel;
use common\model\ReviewRequestNodeModel;
use common\model\TaskModel;
use common\model\UserModel;
use common\service\BehaviorService;
use common\service\TaskService;
use common\service\VersionService;
use Webman\Stomp\Client;

/**
 * 任务审核完毕 消息通知
 *
 * 审核完毕
 *
 * 审核未通过 需要通知之前通过的所有人和提交人
 *
 * 审核通过 需要通知提交人
 *
 * 外部任务审核 需要查询关联的外部任务 以及外部任务审核关系
 */
class TaskReviewResultBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'version' => '',
                'review_request' => '',
                'is_pass' => '',
            ],
            [
                'version' => [],
                'review_request' => [],
                'is_pass' => 0,
            ],
            'data',
            ['type' => 'task_review_result'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($version, $reviewRequest, $isPass) = $params;
        if (($isPass === 0) || empty($version) || empty($reviewRequest)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/
        $notifyMessages = [];
        $task = model(TaskModel::class)->find($version['link_id']);
        $entity = model(EntityModel::class)->find($task['entity_id']);

        $taskService = TaskService::getInstance();
        $parentTask = $taskService->getParentTask($task['id'], $task['project_id'] ?? 0);
        $tenantId = request()->getTenantId();

        $nodes = model(ReviewRequestNodeModel::class)
            ->where([
                'review_request_id' => $reviewRequest['id'],
                'is_reviewed' => "yes",
            ])
            ->order("id ASC")
            ->select();
        $lastReviewerNode = $nodes[count($nodes) - 1];

        $reviewerIdArray = array_column($nodes, 'plan_reviewer', 'plan_reviewer');
        $userIDArray = array_merge($reviewerIdArray, [$task['executor']]);
        $userIDArray = array_unique($userIDArray);

        $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIDArray)]])->select();
        $usersMap = array_column($users, null, 'id');
        $templateId = VersionService::getInstance()->getTaskReviewedMessageTemplateId();
        $executor = $usersMap[$task['executor']] ?? ['name' => 'None', 'union_id' => 0];
        $lastReviewer = $usersMap[$lastReviewerNode['plan_reviewer']] ?? ['name' => 'None'];

        $notifyParam = [
            'first' => '任务审核已完成',
            'task_name' => $entity['name'] . "-" . $task['name'],
            'executor_name' => $executor['name'],
            'reviewer_name' => $lastReviewer['name'],
            'review_at' => date("Y/m/d H:i", $lastReviewerNode['reviewed']),
            'review_result' => $isPass ? "通过" : "未通过",
            'remark' => $isPass ? '请进行下一任务' : '请修改后重新提交审核',
            'task_id' => $task['id'],
            'entity_id' => $task['entity_id'],
        ];

        if ($parentTask && $parentTask['type'] == "shadow" && $tenantId != $parentTask['tenant_id']) {
            /**
             * 当前审核 甲方审核  审核的是外部任务
             *
             */
            //审核外部任务
            //查询外部审核请求数据 通知审核人

            $reviewRequestParam = json_decode($reviewRequest['param'], true);
            $partyBReviewRequestId = $reviewRequestParam['parent_review_request_id'] ?? 0;

            /**
             * 通知乙方审核流的审核人
             */
            if ($partyBReviewRequestId) {
                $partyBReviewRequestNodes = model(ReviewRequestNodeModel::class)
                    ->where([
                        'review_request_id' => $partyBReviewRequestId,
                        'is_reviewed' => "yes",
                        'plan_reviewer' => ['GT', 0],
                    ])
                    ->order("id ASC")
                    ->select();
                $partyBUsers = array_column($partyBReviewRequestNodes, 'plan_reviewer', 'plan_reviewer');
                $userIDArray = array_merge($userIDArray, $partyBUsers);
                $userIDArray = array_unique($userIDArray);

                $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIDArray)]])->select();
                $usersMap = array_column($users, null, 'id');

                foreach ($partyBReviewRequestNodes as $node) {
                    if (empty($usersMap[$node['plan_reviewer']]['union_id'])) {
                        continue;
                    }

                    $notifyParam['first'] = '任务审核已完成';
                    $notifyParam['remark'] = $isPass ? '请进行下一任务' : "请修改后重新提交审核";
                    $notifyMessages[] = [
                        'param' => $notifyParam,
                        'receiver' => $usersMap[$node['plan_reviewer']]['union_id'],
                        'template_id' => $templateId
                    ];
                }
            }
            /**
             *
             * 当审核不通过的时候
             *
             * 通知甲方审核人
             *
             */
            if (!$isPass) {
                $tenant = teamones_request('teamones-im', 'tenant/find', ['param' => [
                    'filter' => [
                        'id' => $parentTask['tenant_id'],
                    ],
                ],
                ])['data'];
                foreach ($nodes as $node) {
                    if ($node['id'] == $lastReviewerNode['id']) {
                        continue;
                    }
                    if (empty($usersMap[$task['executor']]['union_id'])) {
                        continue;
                    }
                    $notifyParam['first'] = '与导演意见不一致';
                    $notifyParam['remark'] = '请进行交流';
                    $notifyParam['executor_name'] = $tenant['name'] ?? 'unknown company name';

                    $notifyMessages[] = [
                        'param' => $notifyParam,
                        'receiver' => $usersMap[$task['executor']]['union_id'],
                        'template_id' => $templateId
                    ];
                }
            }
        } else {
            // 审核内部任务
            $notifyParam['first'] = '任务审核已完成';
            $notifyParam['remark'] = $isPass ? '请进行下一任务' : '请修改后重新提交审核';
            $notifyMessages[] = [
                'param' => $notifyParam,
                'receiver' => $executor['union_id'],
                'template_id' => $templateId
            ];
            // 通过
            if (!$isPass) {
                // 未通过
                foreach ($nodes as $node) {
                    if ($node['id'] == $lastReviewerNode['id']) {
                        continue;
                    }
                    if (empty($usersMap[$node['plan_reviewer']]['union_id'])) {
                        continue;
                    }
                    $notifyMessages[] = [
                        'param' => $notifyParam,
                        'receiver' => $usersMap[$node['plan_reviewer']]['union_id'],
                        'template_id' => $templateId
                    ];
                }
            }
        }

        $messageGenerated = [];
        foreach ($notifyMessages as $message) {
            $messageGenerated[] = [
                "param" => $message['param'],
                'receiver' => $message['receiver'],
                'template_id' => $message['template_id'],
                'content_type' => 'card_message',
                'notice_type' => 'message_task',
                'is_popup' => 1,
                'message_key' => 'task_version_review_result',
            ];
        }

        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
